<?php
include_once "book.php";
include_once "settings.php";

// variable initializing
$bookQuery = array();
$sequenceQuery = array();
$genreQuery = array();
$authorQuery = array();
$translatorQuery = array();



function getFileListFromImportDir($importDir)
{
	// get file list from import dir
	$currentDirContent = scandir($importDir);
	// drop all file which is NOT (.gz OR .fb2)
	foreach ($currentDirContent as $fileNameIndex =>$fileNameValue)
	{
		if (
				(strcmp(mb_substr($fileNameValue,-3,3),".gz")!== 0) &&
				(strcmp(mb_substr($fileNameValue,-4,4),".fb2")!== 0)
		)
		{
			unset($currentDirContent[$fileNameIndex]);
		}
	}
	return $currentDirContent ;
}


// Initial time stamp and log header
$time = microtime(true);
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
print2log($IMPORT_LOG_FILE, " ###########  Import starts " . $today . " ###########" . PHP_EOL) ;



/************  start *** connection to MySQL and initalizing vars. */
$connection = new mysqli($host, $user, $password, $dbname, $port, $socket);
if ($connection->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); }
$connection->set_charset("utf8");

// get sequnce, last inserted ID from book
$res = $connection->query('select max(bookID) from book');
$currentSequence = $res->fetch_array();
$currentSequence = $currentSequence[0];
$initialSequence = $currentSequence ;

// if first load - put current sequence number to zero - 0
if (!isset($currentSequence)) { $currentSequence = 0; } ;
/************ end *** connection to MySQL and initalizing vars. */


$currentDirContent = getFileListFromImportDir($IMPORT_DIR) ;
$books2import = sizeof($currentDirContent);

// taking next (free) bookID.
$currentSequence++;

// MAIN cycle
foreach ($currentDirContent as $currentBookFile)
{

   $currentInportedBook = new Book;
   $currentInportedBook->readDataFromFile($IMPORT_DIR.$currentBookFile) ;
   // Print/Log FB2 parsing log
   print2log($IMPORT_LOG_FILE, "Start working on - " . $currentSequence . " - " . $IMPORT_DIR . $currentBookFile . PHP_EOL . implode($currentInportedBook->FB_LOG,PHP_EOL) . PHP_EOL) ;

   	if ($currentInportedBook->status == "error")
   	{
   		print2log($IMPORT_LOG_FILE, "FATAL ERROR READING FILE - " . $currentInportedBook->fileName . "SKIPPED!" . PHP_EOL) ;
   		continue;
   	}

   // если есть обложка - достать и сложить в covers.

   if (isset($currentInportedBook->binary) and $currentInportedBook->binary != 'default')
   {
		// extract and copy cover picture to ./cover dir
   		 $currentBookCoverFileName = $currentInportedBook->pureFileName."_cover.jpg" ;
		 $currentCoverFileHandle = fopen($COVER_DIR.$currentBookCoverFileName, "w+");
		 fwrite($currentCoverFileHandle, base64_decode($currentInportedBook->binary));
		 fclose ($currentCoverFileHandle) ;
   }
   else
   {
   	$currentBookCoverFileName = 'default';
   }


   // build book query
   $bookQuery[] = "('".
     	$currentSequence. "','".
   		$currentInportedBook->flibustaBookID . "','".
   		$currentInportedBook->fileSize ."','".
   		$connection->real_escape_string($currentInportedBook->pureFileName) ."','".
   		$currentBookCoverFileName ."','".
   		$currentInportedBook->bookType ."','".
   		$connection->real_escape_string($currentInportedBook->book_title) ."','".
   		$connection->real_escape_string($currentInportedBook->keywords) ."','".
		$connection->real_escape_string($currentInportedBook->annotation)."','".
   		$connection->real_escape_string($currentInportedBook->lang) ."','".
   		$connection->real_escape_string($currentInportedBook->srcLang)	."','".
   		$connection->real_escape_string($currentInportedBook->date)	."','".
   		$connection->real_escape_string($currentInportedBook->publisherBookName)."','".
   		$connection->real_escape_string($currentInportedBook->publisherPublisher)."','".
   		$connection->real_escape_string($currentInportedBook->publisherCity)."','".
   		$connection->real_escape_string($currentInportedBook->publisherYear)."','".
   		$connection->real_escape_string($currentInportedBook->publisherISBN).
   		"')" . PHP_EOL;


   // build sequence query
   if (sizeof($currentInportedBook->sequence))
   {
   	 if (is_array($currentInportedBook->sequence))
   	 {
   	 	foreach ($currentInportedBook->sequence as $currentSeq)
   	 	{
   	 		$sequenceQuery[] = "('".
   	 				$currentSequence. "','".
   	 				$connection->real_escape_string(trim($currentSeq['name'])). "','".
   	 				$connection->real_escape_string(trim($currentSeq['number'])).
   	 		"')";
   	 	}
   	 }
   }

   // build genre query
   if ($currentInportedBook->genre)
   {
   	if (is_array($currentInportedBook->genre))
   	{
   		foreach ($currentInportedBook->genre as $currentGenre)
   		{
   			$genreQuery[] = "('".
   					$currentSequence. "','".
   					$currentGenre .
   					"')";
   		}
   	}
   	else
   	{
   			$genreQuery[] = "('". $currentSequence. "','". $connection->real_escape_string(trim($currentInportedBook->genre)) . "')";

   	}

   }
   else
   {
   			$genreQuery[] = "('". $currentSequence. "','unknown')";
   }


   // build author query
   foreach ($currentInportedBook->authorName as $currentAuthor)
   {
   			$authorQuery[] = "('".
   					$currentSequence. "','".
   					$connection->real_escape_string(trim($currentAuthor['first-name'])). "','".
   					$connection->real_escape_string(trim($currentAuthor['middle-name'])). "','".
   					$connection->real_escape_string(trim($currentAuthor['last-name'])). "','".
   					$connection->real_escape_string(trim($currentAuthor['nickname'])). "','".
   					$connection->real_escape_string(trim($currentAuthor['email'])).
   					"')";
   }
   	// build translator query
   	if (sizeof($currentInportedBook->translatorName) > 0)
   	{
   		foreach ($currentInportedBook->translatorName as $currentTranslator)
   		{
   			 $translatorQuery[] = "('".
   					$currentSequence. "','".
   					$connection->real_escape_string(trim($currentTranslator['first-name'])). "','".
   					$connection->real_escape_string(trim($currentTranslator['middle-name'])). "','".
   					$connection->real_escape_string(trim($currentTranslator['last-name'])). "','".
   					$connection->real_escape_string(trim($currentTranslator['nickname'])). "','".
   					$connection->real_escape_string(trim($currentTranslator['email'])).
   					"')";
   		}
   	}





   	$currentSequence++;
  unset($currentInportedBook);

}

print2log($IMPORT_LOG_FILE, $currentSequence - $initialSequence - 1 . " Books was processed" . PHP_EOL) ;

$connection->query('INSERT INTO `genre`
		(
			`bookID`,
			`genreCode`
		)
		VALUES '.implode(',', $genreQuery));

print2log($IMPORT_LOG_FILE, "genre errors" . PHP_EOL . $connection->error . PHP_EOL) ;

$connection->query('INSERT INTO `author`
		(
			`bookID`,
			`authorFirstName`,
			`authorMiddleName`,
			`authorLastName`,
			`authorNickName`,
			`authorEMail`
		)
		VALUES '.implode(',', $authorQuery));
print2log($IMPORT_LOG_FILE, "author errors" . PHP_EOL . $connection->error . PHP_EOL) ;

if (sizeof($translatorQuery) > 0)
{
$connection->query('INSERT INTO `translator`
		(
			`bookID`,
			`translatorFirstName`,
			`translatorMiddleName`,
			`translatorLastName`,
			`translatorNickName`,
			`translatorEMail`
		)
		VALUES '.implode(',', $translatorQuery));

print2log($IMPORT_LOG_FILE, "translator errors" . PHP_EOL . $connection->error . PHP_EOL) ;
}

if (sizeof($sequenceQuery) > 0)
{
$connection->query('INSERT INTO `sequence`
		(
			`bookID`,
			`sequenceName`,
			`sequenceNumber`
		)
		VALUES '.implode(',', $sequenceQuery));

print2log($IMPORT_LOG_FILE, "sequence errors" . PHP_EOL . $connection->error . PHP_EOL) ;
}

$tmp = 'INSERT INTO `book`
		(
			`bookID`,
			`flibustaBookID`,
			`fileSize`,
			`fileName`,
			`coverFileName`,
			`fileType`,
			`title`,
			`keywords`,
			`annotation`,
			`lang`,
			`srcLang`,
			`date`,
			`publisherBookName`,
			`publisherPublisher`,
			`publisherCity`,
			`publisherYear`,
			`publisherISBN`
		)
		VALUES '.implode(',', $bookQuery);
$file = 'book.sql';
file_put_contents($file, $tmp);


$connection->query('
		INSERT INTO `book`
		(
			`bookID`,
			`flibustaBookID`,
			`fileSize`,
			`fileName`,
			`coverFileName`,
			`fileType`,
			`title`,
			`keywords`,
			`annotation`,
			`lang`,
			`srcLang`,
			`date`,
			`publisherBookName`,
			`publisherPublisher`,
			`publisherCity`,
			`publisherYear`,
			`publisherISBN`
		)
		VALUES '.implode(',', $bookQuery));

print2log($IMPORT_LOG_FILE, "books errors" . PHP_EOL . $connection->error . PHP_EOL ) ;

$connection->close();
$time = abs(round($time - microtime(true),2));

print2log($IMPORT_LOG_FILE, $time . " sec". PHP_EOL . "all done" . PHP_EOL ) ;


?>